import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';

import { getTopBannerAction } from '../../store/actionCreators';

import { Carousel } from 'antd';
import { BannerControl, BannerLeft, BannerRight, BannerWrapper } from './style'
const topBanner = memo(() => {
    //往state存储了currentIndex属性值为0 setCurrentIndex是结构出专门操作currentIndex这个属性的
    //并且其他地方直接可以通过currentIndex来获取最新的值
    const [currentIndex, setCurrentIndex] = useState(0)


    //hooks里的useDispatch 这个useDispatch是react-redux提供的
    const dispatch = useDispatch();
    //获取数据  useSelector接收一个回调函数并携带了state(公共池状态)参数
    const topBanners = useSelector(state => {
        //这里的这个get是immutable里获取被immutable管理的值 两次get是因为这两个对象都被immutablejs库所管理了
        // return  state.get("recommend").get("topBanners")
        //immutable的getInAPI可以逐次获取被immutable所管理的值
        return state.getIn(["recommend", "topBanners"])
    }, shallowEqual)
    //发送网络请求
    useEffect(() => {
        //发送网络请求
        dispatch(getTopBannerAction())
    }, [dispatch])//监听dispatch的变化
    //Ref的Hooks
    const bannerRef = useRef()


    //useCallback他会存储里面函数的地址值 避免一个函数
    const bannerChange = useCallback((from,to)=>{
        //更新sate里currentIndex的值
        setCurrentIndex(to)
    },[])
    //这个意思是如果能取到topBanners[currentIndex]就去拿图片地址
    const bgImage = topBanners[currentIndex] && (topBanners[currentIndex].imageUrl+"?imageView&blur=40x20")
    return (
        <BannerWrapper bgImage={bgImage}>
            <div className="banner wrap-v2">
                <BannerLeft>
                    <Carousel effect="fade" autoplay ref={bannerRef}  beforeChange={ bannerChange } >
                        {
                            topBanners.map((item,index)=>{
                                return (
                                    <div className="banner-item" key={item.targetId}>
                                        <img className="image" src={item.imageUrl} alt={item.targetType}/>
                                    </div>
                                )
                            })
                        }
                    </Carousel>,
                </BannerLeft>
                <BannerRight></BannerRight>
                <BannerControl>
                    <button className="btn left"  onClick={e=>bannerRef.current.prev()}></button>
                    <button className="btn right" onClick={e=>bannerRef.current.next()}></button>
                </BannerControl>
            </div>
        </BannerWrapper>
    );
});

export default topBanner;